home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Fritz: All Fritz
/
All Fritz.zip
/
All Fritz
/
FILES
/
PROGSCAL
/
TBUTIL2.LZH
/
QLSORT.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1984-07-13
|
4KB
|
118 lines
CONST max = 1000; {max array size}
TYPE standardarray = ARRAY[0..max] OF STRING[8];
TYPE pointarray = ARRAY[0..max] OF INTEGER;
VAR words : standardarray; {numeric array}
pointer : pointarray;
last,i : INTEGER;
PROCEDURE SWAP( VAR a,b: INTEGER );
VAR t: INTEGER;
BEGIN
t := a;
a := b;
b := t
END;
PROCEDURE bsort( start, top: INTEGER;
VAR arry: standardarray;
VAR pointer: pointarray );
{bubble sort procedure. sorts array from start to top inclusive}
VAR index: INTEGER;
switched: BOOLEAN;
BEGIN {bsort}
repeat
switched := FALSE;
FOR index := start TO top-1 DO
BEGIN
IF arry[pointer[index]] > arry[pointer[index+1]] THEN
BEGIN
SWAP( pointer[index], pointer[index+1] );
switched := TRUE;
END
END;
UNTIL switched = FALSE;
END; {bsort}
PROCEDURE findmedian( start, top: INTEGER;
VAR arry: standardarray;
VAR pointer : pointarray );
{procedure to find a good median value in array and place it}
VAR middle: INTEGER;
sorted: standardarray;
BEGIN {findmedian}
middle := (start + top) DIV 2;
sorted[1] := arry[pointer[start]];
sorted[2] := arry[pointer[top]];
sorted[3] := arry[pointer[middle]];
IF (sorted[2] > sorted[1]) AND (sorted[2] < sorted[3]) THEN
SWAP( pointer[start], pointer[middle] )
ELSE IF (sorted[3] > sorted[1]) AND (sorted[3] < sorted[2]) THEN
SWAP( pointer[start], pointer[top] );
END; {findmedian}
PROCEDURE sortsection( start, top: INTEGER;
VAR arry: standardarray;
VAR pointer : pointarray);
{procedure to sort a section of the main array, and }
{then divide it into two partitions to be sorted }
VAR swapup: BOOLEAN;
s,e,m: INTEGER;
BEGIN {sortsection}
IF top - start < 6 THEN {sort small sections with bsort}
bsort( start, top, arry , pointer )
ELSE
BEGIN
findmedian( start, top, arry , pointer );
swapup := TRUE;
{start scanning from array top}
s := start; {lower comparison limit}
e := top; {upper comparison limit}
m := start; {location of comparison value}
WHILE e > s DO
BEGIN
IF swapup = TRUE THEN
{scan downward from partition top}
{and exchange if smaller than median}
BEGIN
WHILE( arry[pointer[e]] >= arry[pointer[m]] )
AND (e > m) DO
e := e - 1;
IF e > m THEN
BEGIN
SWAP( pointer[e], pointer[m] );
m := e;
END;
swapup := FALSE;
END
ELSE
{scan upward from a partition start}
{and exchange if larger than median}
BEGIN
WHILE( arry[pointer[s]] <= arry[pointer[m]] )
AND (s < m) DO
s := s + 1;
IF s < m THEN
BEGIN
SWAP( pointer[s], pointer[m] );
m := s;
END;
swapup := TRUE;
END
END;
{sort lower half of partition}
sortsection( start, m-1, arry , pointer );
{sort upper half of partition}
sortsection( m+1, top, arry , pointer);
END
END; {sortsection}
BEGIN {qsort - main program}
FOR i := 1 TO max DO
pointer[i] := i;
sortsection( 1, max , words , pointer );
END. {qsort}